package com.demo.BookList.controller;

import com.demo.BookList.model.Book;
import com.demo.BookList.model.BookRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Book 控制层
 * 注意这里的注解使用@Controller，才能正确返回html
 */

@Data
@AllArgsConstructor
@Controller
@RequestMapping("/book")
public class BookController {
    private static final String BOOK_FROM_PATH_NAME="bookForm";
    private static final String BOOK_LIST_PATH_NAME="bookList";
    private static final String REDIRECT_TO_BOOK_URL="redirect:/book";

    @Autowired
    private BookRepository bookRepository;

    /**
     * 获取Book列表
     * 处理"/book"的GET请求，用来获取Book列表
     * @param map
     * @return
     */
    @GetMapping()
    public String getBookList(ModelMap map) {
        map.addAttribute("bookList", bookRepository.findAll());
        return BOOK_LIST_PATH_NAME;
    }

    /**
     * 获取创建Book的表单
     * @param map
     * @return
     */
    @GetMapping("/create")
    public String createBookForm(ModelMap map) {
        map.addAttribute("book", new Book());
        map.addAttribute("action", "create");
        return BOOK_FROM_PATH_NAME;
    }

    /**
     * 创建Book
     * 处理"/book/create"的POST请求，用来创建Book信息
     * @param book
     * @return
     */
    @PostMapping(value = "/create")
    public String postBook(@ModelAttribute Book book) {
        bookRepository.save(book);
        return REDIRECT_TO_BOOK_URL;
    }

    /**
     * 获取更新Book表单
     * 处理"/book/update/{id}"的GET请求，通过URL中的id值获取Book信息
     * URL中的id，通过@Pathvariable绑定参数
     * @param id
     * @param map
     * @return
     */
    @GetMapping("/update/{id}")
    public String getBookForm(@PathVariable Long id, ModelMap map) {
        map.addAttribute("book", bookRepository.findBookById(id));
        map.addAttribute("action", "update");
        return BOOK_FROM_PATH_NAME;
    }

    /**
     * 更新Book
     * 处理"/update"的PUT请求，用来更新Book信息
     * @param book
     * @return
     */
    @PostMapping("/update")
    public String putBook(@ModelAttribute Book book) {
        bookRepository.save(book);
        return REDIRECT_TO_BOOK_URL;
    }

    /**
     * 删除Book
     * 处理"/book/{id}"的DELETE请求，用来删除Book信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteBook(@PathVariable Long id) {
//        System.out.println("准备删除书籍：" + id);
        bookRepository.deleteById(id);
        return REDIRECT_TO_BOOK_URL;
    }
}
